package service;

import model.Session;
import model.Ticket;
import util.LogUtil;

import java.util.*;

public class TicketService {
    private List<Ticket> tickets = new ArrayList<>();
    private SessionService sessionService;

    public TicketService(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    public void buyTicket(Scanner sc, String username) {
        System.out.print("输入场次ID: ");
        int sid = sc.nextInt();
        Session s = sessionService.getSessionById(sid);
        if (s == null) {
            System.out.println("场次不存在！");
            return;
        }
        boolean[][] seats = s.getSeats();
        for (int i = 0; i < seats.length; i++) {
            for (int j = 0; j < seats[i].length; j++) {
                System.out.print(seats[i][j] ? "X " : "O ");
            }
            System.out.println();
        }
        System.out.print("输入排号: ");
        int row = sc.nextInt() - 1;
        System.out.print("输入列号: ");
        int col = sc.nextInt() - 1;
        if (row < 0 || row >= seats.length || col < 0 || col >= seats[0].length || seats[row][col]) {
            System.out.println("座位不可用！");
            return;
        }
        seats[row][col] = true;
        Ticket t = new Ticket(sid, row, col, username, s.getPrice());
        tickets.add(t);
        LogUtil.log("购票", username);
        System.out.println("购票成功！票号:" + t.getId());
    }

    public void refundTicket(Scanner sc, String username) {
        System.out.print("输入票号: ");
        int tid = sc.nextInt();
        for (Ticket t : tickets) {
            if (t.getId() == tid && !t.isRefunded() && t.getUsername().equals(username)) {
                t.setRefunded(true);
                Session s = sessionService.getSessionById(t.getSessionId());
                if (s != null) {
                    s.getSeats()[t.getRow()][t.getCol()] = false;
                }
                LogUtil.log("退票", username);
                System.out.println("退票成功！");
                return;
            }
        }
        System.out.println("未找到可退票！");
    }
}